<template>
  <el-dialog :title="showTitle" :visible.sync="show" :close-on-click-modal="false" :show-close="!btnLoading" width="1200px" @closed="closed">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item prop="prjchkId" class="hide" />
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="项目" prop="projectId">
            <el-select v-model="form.projectId" placeholder="请选择项目" :disabled="isEdit" filterable clearable :loading="prjLoading" style="width: 100%" @change="onChangeProject">
              <el-option v-for="project in projectList" :key="project.fid" :label="project.cflastname" :value="project.fid" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="rdcTypeList.length">
          <el-form-item label="检查单位" prop="rdcType" key="rdcType" :rules="rules.rdcType">
            <el-select v-model="form.rdcType" placeholder="请选择检查单位" :disabled="isEdit" style="width: 100%">
              <el-option v-for="dict in rdcTypeList" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检查人员" prop="principalId">
            <el-input v-model="form.principalUserName" readonly disabled v-if="isEdit" />
            <el-select v-model="form.principalId" placeholder="请选择抽检人员" filterable :loading="principalLoading" style="width: 100%" @change="onChangePrincipalId" v-else>
              <el-option v-for="item in principalList" :key="item.fid" :label="item.nickName" :value="item.fid" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检查日期" prop="checkDate">
            <el-date-picker v-model="form.checkDate" value-format="yyyy-MM-dd" type="date" :disabled="isEdit" placeholder="选择日期" style="width: 100%" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="施工单位" prop="constructionId" style="height: 36px">
            <el-input v-model="form.constructionName" readonly disabled v-if="isEdit" />
            <el-select v-model="form.constructionId" placeholder="请选择施工单位" filterable clearable :loading="constructionLoading" style="width: 100%" @change="onChangeConstructionId" v-else>
              <el-option v-for="item in showConstructionList" :key="item.constructionId + item.sectionId" :label="item.constructionName" :value="item.constructionId" style="height: auto" @click.native.prevent="constructionOptionClick(item)">
                <div style="padding: 5px 0">
                  <div style="font-size: 14px; line-height: 24px">{{ item.constructionName || item.constructionId }}</div>
                  <div style="color: #8492a6; font-size: 12px; line-height: 14px">{{ item.showSectionName }}</div>
                </div>
              </el-option>
              <el-option v-if="constructionScope === 'project'" value="" disabled @click.native.prevent="constructionScope = ''">
                <el-button size="mini" type="text" icon="el-icon-plus">更多</el-button>
              </el-option>
              <el-option v-else value="" disabled @click.native.prevent="showEditRdcConstruction = true">
                <el-button size="mini" type="text" icon="el-icon-plus">添加施工单位</el-button>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="检查标段" prop="sectionId" style="height: 36px">
            <el-input v-model="form.section" readonly disabled v-if="isEdit" />
            <el-select v-model="form.sectionId" placeholder="请选择检查标段" filterable clearable :loading="constructionLoading" style="width: 100%" @change="onChangeSectionId" v-else>
              <el-option v-for="item in sectionConsList" :key="item.sectionId" :label="item.showSectionName" :value="item.sectionId" style="height: auto">
                <div style="padding: 5px 0">
                  <div style="font-size: 14px; line-height: 24px">{{ item.showSectionName }}</div>
                  <div style="color: #8492a6; font-size: 12px; line-height: 14px">{{ item.constructionName || item.constructionId }}</div>
                </div>
              </el-option>
              <el-option v-if="!sectionConsList.length && canAddSection" value="" disabled @click.native.prevent="gotoSectionPage">
                <el-button size="mini" type="text">前往添加项目检查标段</el-button>
              </el-option>
              <el-option v-if="!sectionConsList.length && !canAddSection" value="">
                <div class="add-section-tip">请先添加相关项目检查标段</div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="施工单位" prop="constructionName">
            <el-input v-model="form.constructionName" readonly disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目(检查口径)" prop="inpectionCaliber"><el-input v-model.trim="form.inpectionCaliber" placeholder="请输入检查球号对应名称" :maxlength="255" /></el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="施工单位负责人" prop="constructionUser"><el-input v-model.trim="form.constructionUser" placeholder="请输入施工单位负责人" :maxlength="255" /></el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目总" prop="xmzName">
            <el-input class="fake-selector" readonly v-model="form.xmzName" placeholder="请选择项目总" @click.native="openSelectUser('xmzId', 'xmzName', true)">
              <i slot="append" class="el-icon-arrow-down" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目工程负责人" prop="xmPrincipalName">
            <el-input class="fake-selector" readonly v-model="form.xmPrincipalName" placeholder="请选择项目工程负责人" @click.native="openSelectUser('xmPrincipalId', 'xmPrincipalName', true)">
              <i slot="append" class="el-icon-arrow-down" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目经理" prop="xmjlName">
            <el-input class="fake-selector" readonly v-model="form.xmjlName" placeholder="请选择项目经理" @click.native="openSelectUser('xmjlId', 'xmjlName', true)">
              <i slot="append" class="el-icon-arrow-down" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="集群分管领导" prop="colonyName">
            <el-input class="fake-selector" readonly v-model="form.colonyName" placeholder="请选择集群分管领导" @click.native="openSelectUser('colonyId', 'colonyName', true)">
              <i slot="append" class="el-icon-arrow-down" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="事业部分管领导" prop="businessName">
            <el-input class="fake-selector" readonly v-model="form.businessName" placeholder="请选择事业部分管领导" @click.native="openSelectUser('businessId', 'businessName', true)">
              <i slot="append" class="el-icon-arrow-down" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="陪检专家" prop="expertName">
            <el-input class="fake-selector" readonly v-model="form.expertName" placeholder="请选择陪检专家" @click.native="openSelectUser('expertId', 'expertName', true)">
              <i slot="append" class="el-icon-arrow-down" />
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="描述" prop="description"><el-input v-model="form.description" type="textarea" placeholder="请输入内容" :maxlength="500" /></el-form-item>
    </el-form>

    <el-divider>检查项录入</el-divider>
    <div v-loading="tradeTypeLoading" element-loading-text="检查项目操盘类型">
      <InputMode ref="InputMode" v-model="form.scores" :cfg="cfgInfo" />
      <el-empty :description="showEmptyChkitemDesc" v-if="isEmptyChkitem" />
    </div>

    <div slot="footer">
      <el-button type="primary" :disabled="disableAction" :loading="btnLoading" @click="btnSubmit">确 定</el-button>
      <el-button :disabled="btnLoading" @click="show = false">取 消</el-button>
    </div>

    <SelectUserDialog :show.sync="showSelectUserVisible" :selected="selectedUser" :multi="selectUserOption.multi" :max-num="5" @select="selectUserCallback" />
    <EditRdcConstruction ref="EditRdcConstruction" v-model="showEditRdcConstruction" @ok="getConstructionList" />
    <SimilarDataConfirm ref="SimilarDataConfirm" process-type="civil" @confirm="btnSubmit({ isRepeatEntry: 'allow' })" />
  </el-dialog>
</template>
<script>
// 添加或修改土建过程得分
import store from '@/store'
import auth from '@/plugins/auth'
import { editFormMixin } from '@/utils/mixin'
import { getUserByRoleKey } from '@/api/system/user'
import { selectAuthUserProject } from '@/api/projectInspection/courseCheck'
import { listRdcConstruction, listSectionCons } from '@/api/qualityManage/cq'
import { getProTradeType, saveScores } from '@/api/checkScore/cqEval'
import EditRdcConstruction from '@/views/cq/components/EditRdcConstruction'
import SelectUserDialog from '@/views/components/SelectUserDialog'
import InputMode from '@/views/checkScore/chkitemScore/InputMode'
import SimilarDataConfirm from '@/views/checkScore/chkitemScore/SimilarDataConfirm'

export default {
  components: { EditRdcConstruction, SelectUserDialog, InputMode, SimilarDataConfirm },
  mixins: [editFormMixin],
  dicts: ['cq_eval_rdc_type', 'cq_trade_type'],
  data() {
    return {
      primaryKey: 'prjchkId',
      form: {
        prjchkId: '',
        versionId: '',
        versionCode: '',
        chkitemCode: '',
        landparcelId: '',
        projectId: '',
        projectType: '',
        rdcType: '',
        processType: '',
        principalId: '',
        principalUserName: '',
        tradeType: '',
        constructionId: '',
        constructionName: '',
        constructionUser: '',
        inpectionCaliber: '',
        sectionId: '',
        section: '',
        deliveryTypes: '',
        checkDate: new Date().Format('yyyy-MM-dd'),
        description: '',
        xmzId: '',
        xmzName: '',
        xmPrincipalId: '',
        xmPrincipalName: '',
        xmjlId: '',
        xmjlName: '',
        colonyId: '',
        colonyName: '',
        businessId: '',
        businessName: '',
        expertId: '',
        expertName: '',
        scores: []
      },
      rules: {
        projectId: [{ required: true, message: '请选择项目' }],
        rdcType: [{ required: true, message: '请选择检查单位' }],
        principalId: [{ required: true, message: '请选择检查人员' }],
        checkDate: [{ required: true, message: '请选择日期' }],
        // constructionId: [{ required: true, message: '请选择施工单位' }]
        sectionId: [{ required: true, message: '请选择检查标段' }]
      },
      prjLoading: false,
      projectList: [],
      principalLoading: false,
      principalList: [], // 检查人员
      constructionLoading: false,
      constructionList: [], // 施工单位
      showEditRdcConstruction: false, // 添加施工单位的弹窗
      sectionConsList: [], // 含标段的施工单位(根据项目)
      constructionScope: '', // 施工单位范围，project: 根据项目，空或all: 全部
      cfgInfo: {},
      evalScore: {},
      tradeTypeLoading: false,
      // 选择用户窗口
      showSelectUserVisible: false,
      selectUserOption: { idField: '', nameField: '', multi: false },
      selectedUser: []
    }
  },
  computed: {
    isEdit() {
      return !!this.form.prjchkId
    },
    showTitle() {
      const name = this.cfgInfo?.chkitemName || '检查项得分'
      return `${this.isEdit ? '修改' : '添加'}${name}`
    },
    disableAction() {
      return this.btnLoading || this.tradeTypeLoading
    },
    rdcTypeList() {
      // 检查单位列表
      const list = this.dict?.type.cq_eval_rdc_type || []
      const rdcType = this.cfgInfo.rdcType || ''
      if (!rdcType || !list.length) return []

      const rdcTypes = rdcType.split(',').filter(i => i)
      return list.filter(i => rdcTypes.includes(i.value))
    },
    showConstructionList() {
      // 施工单位下拉列表
      return this.constructionScope === 'project' ? this.sectionConsList : this.constructionList
    },
    canAddSection() {
      // 可访问标段页面且有新增权限
      const list = auth.hasPermi('baseManage:ctGcxSection:list')
      const add = auth.hasPermi('baseManage:ctGcxSection:add')
      return list && add
    },
    filteredCfgInfo() {
      // 根据选中的操盘类型过滤子项
      const { cfgInfo } = this
      const { tradeType } = this.form
      if (!cfgInfo.children?.length || !tradeType) return cfgInfo

      const info = JSON.parse(JSON.stringify(cfgInfo))
      info.children = info.children.filter(i => {
        const str = i.tradeType || ''
        if (!str) return false
        const arr = str.split(',').filter(i => i)
        return arr.includes(tradeType)
      })
      return info
    },
    isEmptyChkitem() {
      return !this.cfgInfo?.children?.length
    },
    showEmptyChkitemDesc() {
      const list = this.dict?.label.cq_trade_type || {}
      const { tradeType } = this.form
      const tradeName = tradeType ? list[tradeType] || '' : ''
      return `项目暂无可用检查项${tradeName ? `(${tradeName})` : ''}`
    }
  },
  created() {
    this.getAuthUserProjectList()
  },
  methods: {
    closed() {
      this.$refs.form.resetFields()
      this.cfgInfo = {}
      this.evalScore = {}
    },
    opened(item = {}, { cfgInfo }) {
      this.evalScore = JSON.parse(JSON.stringify(item))
      this.cfgInfo = cfgInfo
      // this.getProTradeType()
      if (!this.projectList.length) this.getAuthUserProjectList()

      // 新增时需下拉选择检查人员和施工单位
      if (this.isEdit) return
      this.getPrincipalList()
      // this.getConstructionList()
      this.getSectionConsList()
    },
    // 获取授权的用户的项目列表
    async getAuthUserProjectList() {
      this.prjLoading = true
      const res = await selectAuthUserProject({ needUserId: true }).catch(() => false)
      this.prjLoading = false
      if (res === false) return
      this.projectList = res.data || []
    },
    onChangeProject() {
      this.changeXmPrincipal()
      // this.getProTradeType()
      this.getSectionConsList()
    },
    changeXmPrincipal() {
      // 改变项目时，若有 项目总、项目工程负责人、项目经理，则覆盖现有值
      const { projectId } = this.form
      if (!projectId) return

      const list = this.projectList
      const data = list.find(i => i.fid === projectId)
      if (!data) return

      if (data.xmzFids) {
        this.form.xmzId = data.xmzFids
        this.form.xmzName = data.xmzName
      }
      if (data.principalIds) {
        this.form.xmPrincipalId = data.principalIds
        this.form.xmPrincipalName = data.principalNames
      }
      if (data.xmjlId) {
        this.form.xmjlId = data.xmjlId
        this.form.xmjlName = data.xmjlName
      }
    },
    async getProTradeType() {
      // 项目操盘类型
      const { projectId } = this.form
      if (!projectId) return (this.form.tradeType = '')

      this.tradeTypeLoading = true
      const res = await getProTradeType({ projectId }).catch(() => false)
      this.tradeTypeLoading = false
      if (res === false) return

      this.form.tradeType = res.data || ''
    },
    // 获取检查人员
    async getPrincipalList() {
      const userFid = store.getters.user?.fid
      const { form } = this
      // const { projectId } = this.form
      // if (!projectId) return (this.principalList = [])

      // GCCJRY 工程抽检人员
      // const opt = { roleKey: 'GCCJRY', projectId }
      const opt = { roleKey: 'GCCJRY' }
      this.principalLoading = true
      const res = await getUserByRoleKey(opt).catch(() => false)
      this.principalLoading = false
      if (res === false) return (this.principalList = [])

      const data = res.data || []
      this.principalList = data

      // 新增时，若登录用户是抽检人员，自动填入
      if (this.isEdit || form.principalId || !auth.hasRole('GCCJRY') || !userFid) return
      const item = data.find(i => i.fid === userFid)
      if (!item) return
      form.principalId = item.fid
      form.principalUserName = item.nickName
    },
    // 检查人员改变时，手动赋值 principalUserName
    onChangePrincipalId(id) {
      if (!id) return (this.form.principalUserName = '')
      const list = this.principalList || []
      const item = list.find(i => i.fid === id)
      this.form.principalUserName = item?.nickName || ''
    },
    // 获取施工单位
    async getConstructionList() {
      this.constructionLoading = true
      const res = await listRdcConstruction().catch(() => false)
      this.constructionLoading = false
      if (res === false) return
      this.constructionList = res.data || []
    },
    // 根据项目获取含标段的施工单位
    async getSectionConsList() {
      const { projectId } = this.form
      this.constructionScope = ''
      if (!projectId) {
        this.sectionConsList = []
        return this.onChangeSectionId()
      }

      const opt = { curProjectId: projectId, sectionType: 'ENG_SEC' }
      this.constructionLoading = true
      const res = await listSectionCons(opt).catch(() => false)
      this.constructionLoading = false
      if (res === false) return

      const data = res.data || []
      data.map(i => {
        i.showSectionName = i.sectionAlias || i.sectionName
      })
      this.sectionConsList = data
      if (data.length) this.constructionScope = 'project'
      this.onChangeSectionId()
    },
    // 施工单位改变时，手动赋值名称及标段
    onChangeConstructionId(id) {
      if (!id) return (this.form.constructionName = '')
      const list = this.showConstructionList || []
      const item = list.find(i => i.constructionId === id)
      if (!item) return
      this.form.constructionName = item.constructionName || ''
      this.form.sectionId = item.sectionId || ''
      this.form.section = item.showSectionName || ''
    },
    constructionOptionClick(item) {
      if (!item.sectionId) return
      this.form.sectionId = item.sectionId
      this.form.section = item.showSectionName || ''
    },
    // 标段改变时，手动赋值名称及施工单位
    onChangeSectionId(id) {
      const list = this.sectionConsList || []
      const item = id ? list.find(i => i.sectionId === id) || {} : {}
      this.form.sectionId = item.sectionId || ''
      this.form.section = item.showSectionName || ''
      this.form.constructionId = item.constructionId || ''
      this.form.constructionName = item.constructionName || ''
    },
    gotoSectionPage() {
      this.$router.push({ path: '/baseManage/gcxSection' })
    },
    async onSubmit(opts) {
      const { cfgInfo } = this
      const valid = await this.$refs.form.validate().catch(() => false)
      if (!valid) return
      const validScores = await this.$refs.InputMode.validate().catch(() => false)
      if (!validScores) return this.msgInfo('检查项未录入完整，请录入完整后提交')
      if (!this.form.scores?.length) return this.msgInfo('请添加检查项')

      const opt = { ...this.form, processType: 'civil' }
      if (!this.rdcTypeList.length) opt.rdcType = ''
      if (opts?.isRepeatEntry) opt.isRepeatEntry = opts.isRepeatEntry

      if (this.isEdit) {
        this.markRemovedScores(opt)
      } else {
        // opt.versionId = ''
        opt.versionCode = cfgInfo.versionCode
        opt.chkitemCode = cfgInfo.chkitemCode
        // opt.landparcelId = ''
        // opt.projectType = ''
        // opt.deliveryTypes = ''
      }

      this.btnLoading = true
      const res = await saveScores(opt).catch(() => false)
      this.btnLoading = false
      if (res === false) return

      // 已有相似的数据
      if (res.data?.isRepeatEntry === 'duplicate') return this.$refs.SimilarDataConfirm.open({ cfgInfo, data: res.data })

      this.msgSuccess('保存成功')
      this.show = false
      this.$emit('ok')
    },
    markRemovedScores(data) {
      // 标记移除的检查项
      const oldScores = this.evalScore.scores || []
      if (!oldScores.length) return

      const newScores = JSON.parse(JSON.stringify(data.scores || []))
      const scoreIds = newScores.map(i => i.chkitemScoreId).filter(i => i)
      oldScores.map(i => {
        if (scoreIds.includes(i.chkitemScoreId)) return
        newScores.push({ ...i, isDelete: 1 })
      })
      data.scores = newScores
    },
    // 打开选择用户
    openSelectUser(idField, nameField, multi) {
      this.selectUserOption = { idField, nameField, multi: !!multi }
      let selectedUser = []
      const idValue = this.form[idField] || ''
      const nameValue = this.form[nameField] || ''
      const ids = idValue ? idValue.split(',') : []
      const names = nameValue ? nameValue.split(',') : []
      if (ids.length && names.length) {
        selectedUser = ids.map((id, index) => ({ value: id, label: names[index] }))
      }
      this.selectedUser = selectedUser
      this.showSelectUserVisible = true
    },
    // 选择用户回调
    selectUserCallback(selection) {
      const { idField, nameField } = this.selectUserOption
      this.form[idField] = selection.map(i => i.value).join(',')
      this.form[nameField] = selection.map(i => i.label).join(',')
    }
  }
}
</script>
<style lang="scss" scoped>
.add-section-tip {
  color: #c0c4cc;
  font-size: 14px;
  font-weight: normal;
}
.fake-selector {
  cursor: pointer;
  /deep/ {
    .el-input__inner {
      cursor: pointer;
      border-right: none;
      &:hover,
      &:focus {
        border-color: #dcdfe6;
      }
    }
    .el-input-group__append {
      background-color: transparent;
      padding: 0 10px;
    }
  }
}
</style>
